
var productsViewModel;
var placeViewModel;

$(document).ready(function(){
	productsViewModel = new ProductsViewModel();
	placeViewModel = new PlaceViewModel();
	menuViewModel = new MenuViewModel();
	
	ko.applyBindings(productsViewModel, $("#product-content")[0]);
	ko.applyBindings(placeViewModel, $("#place-content")[0]);
	ko.applyBindings(menuViewModel, $("#menu")[0]);
});

function MenuViewModel(){
	var self = this;
	
	self.isLocationOptionVisible = ko.observable(false);
	self.isProductSearchVisible = ko.observable(false);
	
	self.showLocationOption = function(){
		self.isLocationOptionVisible(!self.isLocationOptionVisible());
		if(self.isLocationOptionVisible()){
			$("#panel").fadeIn("slow");	
		}else{
			$("#panel").fadeOut("slow");
		}
	};
	
	self.showProductOption = function(){
		self.isProductSearchVisible(!self.isProductSearchVisible());
		if(self.isProductSearchVisible()){
			$("#products").fadeIn("slow");	
		}else{
			$("#products").fadeOut("slow");
		}
	};
}

function PlaceViewModel(){
	var self = this;
	self.places = ko.observableArray([]);
	self.priceText = ko.observable('');
	self.selectedPlace = ko.observable();
	
	self.updatePricePopinVisible = ko.observable(false);
	
	self.getPlaces = function(lat, lng, radius){
		$.getJSON(contextPath + '/place/getNearbyPlaces', {sLat: lat, sLng: lng, sDist: radius}, function(result) {
			var placeIds = self.placesToArray(result);
			self.places($.map(result, function(place){ return new Place(place); }));
			productsViewModel.setPlaces(placeIds, self.populatePlaces);
	    });
	};
	
	self.populatePlaces = function(){
		map.clearOverlays();
		$.each(self.places(), function(index, value){
			if(productsViewModel.selectedProduct()){
				var placeId = this.id;
				var price = ko.utils.arrayFirst(productsViewModel.prices(), function(item) {
		            return item.place.id === placeId;
		        });
				this.price = price ? price.value : undefined;
			}
			self.addMarker(this);
        });
	};
	
	self.placesToArray = function(places){
		var placeIds = Array();
		for(var i = 0; i < places.length; i++)
		{
			placeIds.push(places[i].id);
		}
		return placeIds;
	};
	
	self.addMarker = function(place){
		var latlng = new google.maps.LatLng(place.latitude, place.longitude);
		var marker = new google.maps.Marker({
			position: latlng,
			optimized: false,
			map: map
		});
		markersArray.push(marker);
		if(place.price){
			var infowindow = new google.maps.InfoWindow();
			infowindow.setContent('<div><strong>' + place.price + '</strong>');
			infowindow.open(map, marker);
		}
		
		//TODO: Continuar con la actualizacion de los precios.
		google.maps.event.addListener(marker, 'click', function() {
			self.selectedPlace(place.id);
			$('#modal-updatePrice').modal('show');
		});
	};
	
	self.onAddPriceSucces = function(response){
		function verifyAuthentication(data){
		   if (isNaN(data) && (data.indexOf("login_hidden_for_ajax")!= -1)){
			   //if got here then data is a loginform => login required 
			   return false;
		   }
		   // data is not a login form => return true to continue with function processing
		   return true;    
		}
		
		if(!verifyAuthentication(response)){
			$('#modal-updatePrice').modal('hide');
			$('#modal-login').modal('show');
		}
	};
	
	self.addPrice = function(){
		var params = { itemId: productsViewModel.selectedProduct().id, placeId: self.selectedPlace(), value: self.priceText() };
		postService(contextPath + '/price/addPrice', params, self.onAddPriceSucces, function(){});
	};
}

function Place(data){
	var self = this;
	self.id = data.id;
	self.latitude = data.latitude;
	self.longitude = data.longitude;
	self.price;
}

function ProductsViewModel(){
	var self = this;
	self.placeIds;
	self.prices = ko.observableArray([]);
	self.products = ko.observableArray([]);
	self.selectedProduct = ko.observable();
	
	self.productListVisible = ko.computed(function(){
		return self.products().length > 0;
	});
	
	self.addProduct = function(product){
		var match = ko.utils.arrayFirst(self.products(), function(item) {
            return item.id === product.id;
        });
		
		if(!match){
			self.products.push(product);
			self.selectProduct(product);
		}
	};
	
	self.removeProduct = function(product){
		self.products.remove(product);
	};
	
	self.removeAllProducts = function(){
		self.products.removeAll();
	};
	
	self.selectProduct = function(product){
		self.selectedProduct(product);
		self.loadPrices(placeViewModel.populatePlaces);
	};
	
	self.setPlaces = function(placesIds, onSetPlacesSuccess){
		self.placeIds = placesIds;
		self.loadPrices(onSetPlacesSuccess);
	};
	
	self.loadPrices = function(onLoadProductSucces){
		if(!self.placeIds || !self.selectedProduct()){
			self.prices([]);
			onLoadProductSucces();
			return;
		}
		$.ajax({
			traditional: true,
		    type: 'POST',
		    url: contextPath + '/price/getPricesByItemAndPlaces',
		    data: {'itemId': self.selectedProduct().id, 'placesIds': self.placeIds },
		    datatype: 'json',
		    success: function( data ) {
		    	self.prices(data);
		    	onLoadProductSucces();
		    }
		});
	};
	
	self.showProductList = function(){
		self.productListVisible(!self.productListVisible());
	};
}

function Product(id, name){
	var self = this;
	self.id = id;
	self.name = name;
}

/////////////////////////////////////////////////////////////////////////////
function ajaxLogin(form, suffix){
     
    var my_callback = 'placeViewModel.addPrice()'; // The original function which accessed the protected resource
    var user_pass = form.j_password.value;
    var user_name = form.j_username.value; 
 
	//Ajax login - we send credentials to j_spring_security_check (as in form based login
    $.ajax({
          url: contextPath + "/j_spring_security_check",    
          data: { j_username: user_name , j_password: user_pass }, 
          type: "POST",
          beforeSend: function (xhr) {
             xhr.setRequestHeader("X-Ajax-call", "true");
          },
          success: function(result) {       
	          //if login is success, hide the login modal and
	          //re-execute the function which called the protected resource
	          //(#7 in the diagram flow)
	          if (result == "ok") {
	  
	            $("#error-message").hide();            
	            $('#modal-login').modal('hide');
	            if (my_callback!=null && my_callback!='undefined' && my_callback!=''){
	            eval(my_callback.replace(/_/g,'"'));
	            }
	             
	            return true;
	          }else {           
	        	  $("#error-message").show();
	            //$("#ajax_login_error_"+ suffix).html('<span  class="alert display_b clear_b centeralign">Bad user/password</span>') ;
	            return false;           
	          }
    	  },
	      error: function(XMLHttpRequest, textStatus, errorThrown){
	          //$("#ajax_login_error_"+ suffix).html("Bad user/password") ;
	    	  $("#error-message").show();
	          return false; 
	      }
	});
}